/**
 * 
 */
package com.huarui.desktop.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.huarui.desktop.model.TableColumnInfo;
import com.huarui.desktop.model.TableMetaData;

/**
 * @author sunpeng
 * 
 */
public class TableInfoDaoImpl extends SqlMapClientDaoSupport implements TableInfoDao {

	// private
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.huarui.desktop.dao.TableInfoDao#selectTableInfo(java.lang.String)
	 */
	@Override
	public TableMetaData selectTableMetaData(String table) {
		PreparedStatement pstmt = null;
		TableMetaData tableMetaData = new TableMetaData(table);
		try {
			Connection con = super.getSqlMapClientTemplate().getDataSource().getConnection();
			pstmt = con.prepareStatement("select * from " + table + " limit 1,1");
			pstmt.execute(); // 这点特别要注意:如果是Oracle而对于mysql可以不用加.
			ResultSetMetaData rsmd = (ResultSetMetaData) pstmt.getMetaData();
			TableColumnInfo[] columns = new TableColumnInfo[rsmd.getColumnCount()];
			for (int i = 0, len = rsmd.getColumnCount(); i < len; i++) {
				columns[i] = new TableColumnInfo();
				columns[i].setName(rsmd.getColumnName(i + 1));
				columns[i].setClassName(rsmd.getColumnClassName(i + 1));
				columns[i].setLabel(rsmd.getColumnLabel(i + 1));
				columns[i].setType(rsmd.getColumnType(i + 1));
				columns[i].setTypeName(rsmd.getColumnTypeName(i + 1));
				columns[i].setDisplaySize(rsmd.getColumnDisplaySize(i + 1));
			}
			tableMetaData.setColumns(columns);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (pstmt != null) {
				try {
					pstmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
		return tableMetaData;
	}

}
